/**
 *
 * Copyright Pact Lab of H.I.T.
 *
 * Designed and Implemented by Grid Researching Group, 
 * Pact Lab, Harbin
 * 
 * This Project is part of the national 973 Project:
 * Internet Based Virtual Computing Environment
 *
 * http://pact518.hit.edu.cn
 * 
 * Author:       Meteor <meteorlxk@gmail.com> 
 * Copyright:    pact518 
 * Version:      1.0
 * Created:      2009-5-8 
 * LastModified: 2009-5-8
 */
package edu.hit.pact.pgse.crawler.finish;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.hit.pact.pgse.bean.TaskPieceProperty;
import edu.hit.pact.pgse.bean.TaskPieceStatistics;
import edu.hit.pact.pgse.communication.message.AbstractMessage;
import edu.hit.pact.pgse.communication.message.TaskPieceStatisticsMessage;
import edu.hit.pact.pgse.crawler.CrawlerManager;
import edu.hit.pact.pgse.util.AbstractThread;
import edu.hit.pact.pgse.util.Md5Sum;

/**
 * @author meteorlxk
 *
 */
public class FinishedReportedProcessor extends AbstractThread{
	private static final int DEFAULT_INTERVAL = 2; //60 seconds
	
	private Log logger;
	
	private CrawlerManager crawlerManager;
	private TaskPieceProperty pieceProperty;
//	private PrintWriter pw = null;
	
	public FinishedReportedProcessor(CrawlerManager crawlerManager, TaskPieceProperty pieceProperty) {
		this(LogFactory.getLog(FinishedReportedProcessor.class), crawlerManager, pieceProperty);
	}
	
	public FinishedReportedProcessor(Log logger, CrawlerManager crawlerManager, TaskPieceProperty pieceProperty) {
		super(logger, DEFAULT_INTERVAL, true);
		
		this.logger = logger;
		
		this.pieceProperty = pieceProperty;
		this.crawlerManager = crawlerManager;
		String hostName = String.valueOf(Md5Sum.getMd5LongSum(pieceProperty.getPiece().getHomePage()));
//		try {
//			this.pw = new PrintWriter(new FileOutputStream(hostName, true), true);
//			pw.println("todo clean");
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

	/* (non-Javadoc)
	 * @see edu.hit.pact.pgse.util.AbstractThread#mainRun()
	 */
	@Override
	public void mainRun() {
		logger.info("finished report processor is alive");
		
//		pw.println(pieceProperty.getTodoUrlQueueRemain() +" "+pieceProperty.getCleanUrlQueueRemain());

		if (FinishChecker.isFinish(logger, pieceProperty)) {
			logger.error("invoke the crawler manager method");
			TaskPieceStatistics statistics = pieceProperty.toStatistics();
			crawlerManager.processFinishedNotify(statistics);
			
			pieceProperty.setStatus(TaskPieceProperty.FINISHED_AND_REPORTED);
//			pw.close();
			setDeadLoop(false);
			logger.info("finished report is sent out and kill finish report processor");
			return;
		}
	}
}
